package cards

import (
	"github.com/shopspring/decimal"
	"wzgames/internal/gvalidator"
	"wzgames/internal/model/gamep"
	"wzgames/pkg/utils/stringutil"
)

// 扑克

const (
	DiamondStr = "D" // 方块
	ClubStr    = "C" // 梅花
	SpadeStr   = "S" // 黑桃
	HeartStr   = "H" // 红心
)

const (
	Ace   = "A"
	King  = "K"
	Queen = "Q"
	Jack  = "J"
)

var (
	CardRankOrder = []gamep.CardRank{
		gamep.CardRank_TWO,
		gamep.CardRank_THREE,
		gamep.CardRank_FOUR,
		gamep.CardRank_FIVE,
		gamep.CardRank_SIX,
		gamep.CardRank_SEVEN,
		gamep.CardRank_EIGHT,
		gamep.CardRank_NINE,
		gamep.CardRank_TEN,
		gamep.CardRank_JACK,
		gamep.CardRank_QUEEN,
		gamep.CardRank_KING,
		gamep.CardRank_ACE,
	}

	CardSuiteOrder = []gamep.CardSuite{gamep.CardSuite_DIAMOND, gamep.CardSuite_HEART, gamep.CardSuite_SPADE, gamep.CardSuite_CLUB}

	// 一副牌 没有大小鬼
	cardNum = decimal.NewFromInt32(52)
)

// String2Card 字符转Card，如 C2、D3、SK => Card
func String2Card(card string) gamep.Card {
	var suite gamep.CardSuite
	var rank gamep.CardRank
	ok := true
	switch card[:1] {
	case DiamondStr:
		suite = gamep.CardSuite_DIAMOND
	case ClubStr:
		suite = gamep.CardSuite_CLUB
	case SpadeStr:
		suite = gamep.CardSuite_SPADE
	case HeartStr:
		suite = gamep.CardSuite_HEART
	default:
		suite = gamep.CardSuite_Unknown
		ok = false
	}
	part := card[1:]
	switch part {
	case Ace:
		rank = gamep.CardRank_ACE
	case King:
		rank = gamep.CardRank_KING
	case Queen:
		rank = gamep.CardRank_QUEEN
	case Jack:
		rank = gamep.CardRank_JACK
	default:
		if !gvalidator.IsNumeric(part) {
			rank = gamep.CardRank_ZERO
			ok = false
		} else {
			v, e := stringutil.ToInt32(part, 0)
			if e != nil || v < 2 || v > 10 {
				rank = gamep.CardRank_ZERO
				ok = false
			} else {
				rank = gamep.CardRank(v)
			}
		}
	}
	if ok {
	}
	return gamep.Card{
		Suite: suite,
		Rank:  rank,
	}
}

// Card2String Card转字符，Card => C2、D3、SK...
func Card2String(card *gamep.Card) string {
	if card == nil {
		return ""
	}
	var suiteStr string
	switch card.Suite {
	case gamep.CardSuite_DIAMOND:
		suiteStr = DiamondStr
	case gamep.CardSuite_CLUB:
		suiteStr = ClubStr
	case gamep.CardSuite_SPADE:
		suiteStr = SpadeStr
	case gamep.CardSuite_HEART:
		suiteStr = HeartStr
	}

	return suiteStr + CardRankFormat(card.Rank)
}

// CardRankFormat 牌符号 2, 3, 4 .... 10, J, Q, K, A
func CardRankFormat(rank gamep.CardRank) string {
	switch rank {
	case gamep.CardRank_ACE:
		return Ace
	case gamep.CardRank_KING:
		return King
	case gamep.CardRank_QUEEN:
		return Queen
	case gamep.CardRank_JACK:
		return Jack
	default:
		return stringutil.ToString(rank.Number())
	}
}

// RandCard 从52张里随机一张Card
func RandCard(num float64) gamep.Card {
	v1 := decimal.NewFromFloat(num).Mul(cardNum)
	idx := int32(v1.IntPart())
	suiteIdx := idx % 4
	suite := CardSuiteOrder[suiteIdx]
	rankIdx := idx / 4
	rank := CardRankOrder[rankIdx]

	return gamep.Card{
		Suite: suite,
		Rank:  rank,
	}
}
